from flask import Flask, request, render_template, redirect, url_for
import pymysql
import datetime

app = Flask(__name__,static_folder='static', template_folder='templates')

# 数据库配置
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': '20020502dta',
    'db': 'diary_db',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}


# 主页路由，显示历史记录
@app.route('/')
def index():
    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            sql = "SELECT * FROM diaries ORDER BY date DESC"
            cursor.execute(sql)
            diaries = cursor.fetchall()
        return render_template('index.html', diaries=diaries)
    finally:
        connection.close()


# 提交日记路由
@app.route('/submit', methods=['POST'])
def submit():
    weather = request.form['weather']
    mood = request.form['mood']
    events = request.form['events']
    date = datetime.datetime.now().date()

    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            sql = "INSERT INTO diaries (date, weather, mood, events) VALUES (%s, %s, %s, %s)"
            cursor.execute(sql, (date, weather, mood, events))
        connection.commit()
        return redirect(url_for('index'))
    finally:
        connection.close()


if __name__ == '__main__':
    app.run( debug=True)
